<template>
	<div class="layout">
		<div class="bigDiv">
			<div class="leftDiv">
				<img src="@/assets/image/login/bg.png" style="margin-top: 50px"></img>
			</div>
			<div class="rightDiv">
				<div class="loginTypeDiv">
					<span @click="changeTab(1)" :class="loginType == 1 ? 'loginTypeSelect loginType' : 'loginType'">账号密码登录</span>
					<span style="padding: 0 10px">|</span>
					<span @click="changeTab(2)" :class="loginType == 2 ? 'loginTypeSelect loginType' : 'loginType'">手机验证码登录</span>
				</div>
        <el-form v-if="show && loginType == 1" class="loginForm" ref="loginForm1" :model="loginPwMsg" :rules="loginPwRules">
          <el-form-item label="" prop="userName">
            <div class="inputDiv">
              <el-input  v-model.trim="loginPwMsg.userName" class="loginInput" placeholder="用户名" maxLength="20" :clearable="true"></el-input>
            </div>
          </el-form-item>

          <el-form-item label="" prop="password">
            <div class="inputDiv">
              <el-input v-model.trim="loginPwMsg.password" class="loginInput" :type="pwInputtype" maxLength="20" placeholder="密码">
                <i slot="suffix" class="el-input__icon el-icon-view" @click="pwInputtype = (pwInputtype == 'password' ? 'text' : 'password')"></i>
              </el-input>
            </div>
          </el-form-item>

          <el-form-item label="" prop="authCode">
            <div class="inputDiv">
              <el-input v-model.trim="loginPwMsg.authCode" class="loginInput" placeholder="图形验证码" maxLength="2"></el-input>
              <img class="captchaImg" :src="captchaImage" @click="getCaptchaImage">
            </div>
          </el-form-item>

					<div class="loginBtn" @click="loginByPw">登 录</div>
					<div class="guideDiv">
						<span class="guide" @click="$router.push({path: 'forgotPassword'})">忘记密码</span>
						<span> | </span>
						<span class="guide" @click="$router.push({path: 'register'})">帐号注册</span>
					</div>
        </el-form>
        <el-form v-if="show && loginType == 2" class="loginForm" ref="loginForm2" :model="loginTextMsg" :rules="loginTextRules">
          <el-form-item label="" prop="userPhone">
            <div class="inputDiv">
              <el-input v-model.trim="loginTextMsg.userPhone" class="loginInput" placeholder="手机号码" @input="loginTextMsg.userPhone = loginTextMsg.userPhone.replace(/[^0-9]/g, '')" maxLength="11" :clearable="true"></el-input>
            </div>
          </el-form-item>

          <el-form-item label="" prop="authCode">
            <div class="inputDiv">
              <el-input v-model.trim="loginTextMsg.authCode" class="loginInput" maxLength="6" placeholder="验证码"></el-input>
              <div class="authCodeBtn" @click="sendAuthCode" v-show="textCount < 0">获取验证码</div>
              <div class="cantSendBtn" v-show="textCount >= 0">{{'已发送(' + (textCount < 10 ? ('0' + textCount) : textCount) + '秒)'}}</div>
            </div>
          </el-form-item>

					<div class="loginBtn" @click="loginByText">登 录</div>
        </el-form>
			</div>
		</div>
	</div>
</template>

<script>
import login from '@/formRules/userAccount/login.js';
import {
  setToken,
  getLastUrl,
  clearLastUrl,
} from "@/utils/util.js";
import { mapMutations } from 'vuex';
import { loginByPw, loginByText, getLoginQT } from "@/common/api/logOrReg.js";
import { getCaptchaImage, getAuthCode, getCompanyInfo } from "@/common/api.js";

export default {
  name: "login",
  mixins: [login],
  data() {
    return {
      show: true,
      loginType: 1,
      captchaImage: "",
      pwInputtype: "password",
      textCount: -1, //短信倒计时
      login: "", //登录返回的参数
    };
  },
  methods: {
    ...mapMutations(['setCompanyInfo']),
    // 这样写避免表单切换时出现提示错位
    changeTab(num) {
      this.show = false
      this.$nextTick(() => {
        this.loginType = num
        this.show = true
      })
    },
    /**
     * 获取图片验证码
     */
    async getCaptchaImage() {
      let res = await getCaptchaImage()
      this.captchaImage = "data:image/gif;base64," + res.img;
      this.loginPwMsg.uuid = res.uuid;
    },
    /**
     * 账号登录事件
     */
    async loginByPw() {
      let ok = false
      this.$refs["loginForm1"].validate(valid => {
        if(valid) ok = true;
      })
      if(!ok) return ;
      let res = await loginByPw(this.loginPwMsg);
      console.log("res",res)
      if (res.code == 200) {
        this.login = res;
        localStorage.setItem("login", JSON.stringify(this.login) || "{}");
        this.getCompanyInfo(res.token, res.qtUserName, res.qtPassWord);
      } else if (res.code == 204) {
        this.$confirm(res.msg, "提示", {
          confirmButtonText: "忘记密码",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          this.$router.push({ path: "forgotPassword" });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
      } else {
        this.$message.error(res.msg);
        this.getCaptchaImage();
      }
    },
    /**
     * 发送短信验证码
     */
    async sendAuthCode() {
      let ok = false
      this.$refs["loginForm2"].validateField('userPhone', (valid) => {
        console.log("valid",valid)
        if(!valid) ok = true;
      })
      if(!ok) return ;
      
      let data = {
        userPhone: this.loginTextMsg.userPhone,
        authType: "login",
      };
      let res = await getAuthCode(data)
      console.log("res",res)
      if (res.code == 200) {
        this.textCount = 120;
        var timer = setInterval(counting, 1000);
        function counting() {
          this.textCount--;
          if (this.textCount < 0) {
            clearInterval(timer);
          }
        }
      } else if (res.code == 204) {
        this.$confirm(res.msg, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          this.$router.push({ path: "forgotPassword" });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
      } else {
        this.$message.error(res.msg);
      }
    },
    /**
     * 短信登录事件
     */
    async loginByText() {
      let ok = false
      this.$refs["loginForm2"].validate(valid => {
        console.log("valid",valid)
        if(valid) ok = true;
      })
      if(!ok) return ;
      let res = await loginByText(this.loginTextMsg)
      if (res.code == 200) {
        this.login = res;
        localStorage.setItem("login", JSON.stringify(this.login) || "{}");
        this.getCompanyInfo(res.token, res.qtUserName, res.qtPassWord);
      } else {
        this.$message.error(res.msg);
      }
    },
    async getCompanyInfo(token, qtUserName, qtPassWord) {
      setToken(token);
      let params = {
        clueSource: this.login.clueSource
      };
      let res = await getCompanyInfo(params)
      if(res.code == 200) {
        this.setCompanyInfo(res.data)
        let lastUrl = getLastUrl()
        // console.log(lastUrl)
        if (lastUrl == "" || lastUrl == undefined) {
          this.$router.push({ path: "index" });
        } else {
          let m = lastUrl.match(/login/);
          if (m) {
            this.$router.push("index");
          } else {
            this.$router.replace(lastUrl);
          }
          clearLastUrl();
        }
      } else {
        this.$message.error(res.msg || '获取企业信息失败');
      }
      this.getLogin(qtUserName, qtPassWord);
    },
    // qt登录接口
    async getLogin(account, password) {
      let obj = {
        account,
        password,
        loginType: "PASSWORD",
      };
      let res = await getLoginQT(obj);
      if (res.status == 200) {
        localStorage.setItem("qtToken", res.result.token);
      }
    },
  },
  async mounted() {
    this.getCaptchaImage();
  },
  // 路由导航 -
  beforeRouteEnter(to, from, next) {
    from.meta.keepAlive ? (from.meta.keepAlive = false) : "";
    next();
  },
};
</script>

<style scoped>
.bigDiv {
  margin: 0 auto;
  margin-top: 50px;
  margin-bottom: 250px;
  width: 1000px;
  display: flex;
  justify-content: center;
}

.rightDiv {
  width: 500px;
  margin-left: 30px;
}

.rightDiv .loginTypeDiv {
  display: flex;
  align-items: center;
}

.rightDiv .loginTypeDiv span {
  color: #bbbbbb;
  font-size: 18px;
  transition: all 0.2s ease 0s;
}

.rightDiv .loginTypeDiv .loginType:hover {
  cursor: pointer;
}

.rightDiv .loginTypeDiv .loginTypeSelect {
  color: #333333;
  font-size: 20px;
  transition: all 0.2s ease 0s;
}

.rightDiv .loginForm {
  margin-top: 30px;
}

::v-deep .rightDiv .loginForm .el-input__inner {
  border-radius: 0;
  border-width: 0;
}

.rightDiv .loginForm .inputDiv {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eeeeee;
  height: 70px;
  margin-bottom: 10px;
}

.rightDiv .loginForm .inputDiv .captchaImg {
  height: 40px;
}

.rightDiv .loginForm .inputDiv .authCodeBtn {
  color: #045db9;
  font-size: 14px;
  white-space: nowrap;
}

.rightDiv .loginForm .inputDiv .authCodeBtn:hover {
  cursor: pointer;
  text-decoration: underline;
}

.rightDiv .loginForm .inputDiv .cantSendBtn {
  font-size: 14px;
  color: #999999;
  white-space: nowrap;
}

.loginBtn {
  background-color: #045db9;
  color: #ffffff;
  padding: 10px 0;
  border-radius: 5px;
  margin-top: 30px;
}

.loginBtn:hover {
  cursor: pointer;
  box-shadow: 5px 5px 5px #e1e1e1;
  transition: all 0.2s ease 0s;
}

.errorMsg {
  color: #fc5522;
  font-size: 15px;
  text-align: left;
  margin-top: 20px;
}

.guideDiv {
  margin-top: 20px;
  text-align: right;
  font-size: 13px;
  color: #6490a7;
}

.guideDiv .guide:hover {
  cursor: pointer;
  text-decoration: underline;
}

.layout {
  min-height: 100vh;
  position: relative;
  padding-bottom: 150px;
  box-sizing: border-box;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
}
</style>
